<?php

namespace app\admin\controller;

use think\Db;

class Operate extends Common
{
    public function contact()
    {
        $user_id = input('user_id');

        if (request()->isAjax()) {
            $post = input('post.');

            $current_time = time();

            Db::name('user')->where('id', $user_id)->update(['is_contact' => $post['is_contact']]);

            if ($post['is_contact']) {
                $contact = Db::name('operate_user_contact')->where('user_id', $user_id)->find();

                $data = $post;
                if (isset($data['contact_time'])){
                    $data['contact_time'] = strtotime($data['contact_time']);
                }

                $data['user_id'] = $user_id;
                $data['update_time'] = $current_time;
                unset($data['is_contact']);

                if ($contact) {
                    Db::name('operate_user_contact')->where(['id' => $contact['id']])->update($data);
                } else {
                    $data['create_time'] = $current_time;

                    Db::name('operate_user_contact')->insert($data);
                }
            } else {
                Db::name('operate_user_contact')->where('user_id', $user_id)->delete();
            }

            return ['ret' => '修改成功'];
        } else {
            $data = Db::name('user t1')
                ->field('t1.is_contact, t2.*')
                ->join('operate_user_contact t2', 't2.user_id = t1.id', 'LEFT')
                ->where(['t1.id' => $user_id])
                ->find();

            $this->assign('data', $data);

            return $this->fetch();
        }
    }
}
